//
//  ZZConfirmOrderViewController.m
//  ZuZuBao
//
//  Created by Felix on 2024/4/18.
//

#import "ZZConfirmOrderViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "ZZLoginViewController.h"

@interface ZZConfirmOrderViewController ()

@property (nonatomic, strong) UIScrollView * scrollView;
@property (nonatomic, strong) UIImageView * imgView;
@property (nonatomic, strong) UILabel * titLabel;
@property (nonatomic, strong) UILabel * priceLabel;

@property (nonatomic, strong) UILabel * rentPriceLabel;
@property (nonatomic, strong) UILabel * depositPriceLabel;
@property (nonatomic, strong) UILabel * sendPriceLabel;

@property (nonatomic, strong) UITextField * nameTxField;
@property (nonatomic, strong) UITextField * phoneTxField;
@property (nonatomic, strong) UITextField * addressTxField;

@property (nonatomic, strong) UILabel * orderPriceLabel;
@property (nonatomic, strong) UIButton * rentButton;

@property (nonatomic, assign) double rentPrice;
@property (nonatomic, strong) NSString * oripay;

@end

@implementation ZZConfirmOrderViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.rentPrice = self.model.orderFee * 30;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"确认订单";
    self.view.backgroundColor = [UIColor whiteColor];

    [self createView];
    [self getData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)createView {
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kNavBarHeight, kScreenWidth, kScreenHeight - kNavBarHeight - kSafeBottomHeight - 56)];
    self.scrollView.backgroundColor = kBackColor;
    [self.view addSubview:self.scrollView];
    
    UIView * wView = [[UIView alloc] initWithFrame:CGRectMake(kPadding, 10, kScreenWidth - kPadding * 2, 112)];
    wView.backgroundColor = [UIColor whiteColor];
    wView.layer.cornerRadius = 12;
    wView.layer.masksToBounds = YES;
    [self.scrollView addSubview:wView];
    
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(12, 16, 80, 80)];
    self.imgView.contentMode = UIViewContentModeScaleAspectFit;
    [wView addSubview:self.imgView];
    
    self.titLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.imgView.frame) + 12, self.imgView.frame.origin.y, wView.frame.size.width - 12 - 80 - 12 - 17, 24)];
    self.titLabel.textColor = k333Color;
    self.titLabel.font = [UIFont boldSystemFontOfSize:16];
    [wView addSubview:self.titLabel];
    
    self.priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.imgView.frame) + 10, CGRectGetMaxY(self.imgView.frame) - 22, 100, 22)];
    self.priceLabel.textColor = kRGBAColor(0xFF0000, 1);
    self.priceLabel.font = [UIFont boldSystemFontOfSize:18];
    [wView addSubview:self.priceLabel];
    
    UIView * wView2 = [[UIView alloc] initWithFrame:CGRectMake(kPadding, CGRectGetMaxY(wView.frame) + 10, kScreenWidth - kPadding * 2, 155)];
    wView2.backgroundColor = [UIColor whiteColor];
    wView2.layer.cornerRadius = 12;
    wView2.layer.masksToBounds = YES;
    [self.scrollView addSubview:wView2];
    
    NSArray * array = @[@"租期", @"租金", @"押金", @"运费"];
    CGFloat height = (155 - 6) / 4;
    for (int i = 0; i < array.count; i++) {
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(12, 6 + height * i, 60, height)];
        label.textColor = k333Color;
        label.font = [UIFont systemFontOfSize:14];
        label.text = array[i];
        [wView2 addSubview:label];
    }
    
    NSArray * array2 = @[@"1个月", @"2个月", @"3个月"];
    CGFloat width = 58;
    for (int i = 0; i < array2.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(wView2.frame.size.width - 12 - width*3 + width*i, 16, width, 26);
        button.backgroundColor = [UIColor whiteColor];
        button.layer.cornerRadius = 13;
        button.layer.masksToBounds = YES;
        [button setTitleColor:k333Color forState:UIControlStateNormal];
        [button setTitle:array2[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.titleLabel.adjustsFontSizeToFitWidth = YES;
        button.tag = 1000 + i;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [wView2 addSubview:button];
        
        if (i == 0) {
            button.backgroundColor = kRGBAColor(0x5F6FFF, 1);
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
    
    self.rentPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(wView2.frame.size.width - 12 - 100, 6 + height, 100, height)];
    self.rentPriceLabel.textColor = k333Color;
    self.rentPriceLabel.font = [UIFont systemFontOfSize:14];
    self.rentPriceLabel.textAlignment = NSTextAlignmentRight;
    [wView2 addSubview:self.rentPriceLabel];
    
    self.depositPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(wView2.frame.size.width - 12 - 100, 6 + height*2, 100, height)];
    self.depositPriceLabel.textColor = k333Color;
    self.depositPriceLabel.font = [UIFont systemFontOfSize:14];
    self.depositPriceLabel.textAlignment = NSTextAlignmentRight;
    [wView2 addSubview:self.depositPriceLabel];
    
    self.sendPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(wView2.frame.size.width - 12 - 100, 6 + height*3, 100, height)];
    self.sendPriceLabel.textColor = k333Color;
    self.sendPriceLabel.font = [UIFont systemFontOfSize:14];
    self.sendPriceLabel.textAlignment = NSTextAlignmentRight;
    [wView2 addSubview:self.sendPriceLabel];
    
    UIView * wView3 = [[UIView alloc] initWithFrame:CGRectMake(kPadding, CGRectGetMaxY(wView2.frame) + 10, kScreenWidth - kPadding * 2, 195)];
    wView3.backgroundColor = [UIColor whiteColor];
    wView3.layer.cornerRadius = 12;
    wView3.layer.masksToBounds = YES;
    [self.scrollView addSubview:wView3];
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(12, 15, 120, 16)];
    label.textColor = k333Color;
    label.font = [UIFont systemFontOfSize:14];
    label.text = @"请填写收货信息";
    [wView3 addSubview:label];
    
    self.nameTxField = [[UITextField alloc] initWithFrame:CGRectMake(12, CGRectGetMaxY(label.frame) + 10, wView3.frame.size.width - 12 * 2, 38)];
    self.nameTxField.backgroundColor = kRGBAColor(0xF2F5F9, 1);
    self.nameTxField.layer.cornerRadius = 8;
    self.nameTxField.layer.masksToBounds = YES;
    self.nameTxField.placeholder = @"请输入收货人姓名";
    self.nameTxField.textColor = k333Color;
    self.nameTxField.font = [UIFont systemFontOfSize:14];
    self.nameTxField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 12, 38)];
    self.nameTxField.leftViewMode = UITextFieldViewModeAlways;
    [wView3 addSubview:self.nameTxField];
    
    self.phoneTxField = [[UITextField alloc] initWithFrame:CGRectMake(12, CGRectGetMaxY(self.nameTxField.frame) + 10, wView3.frame.size.width - 12 * 2, 38)];
    self.phoneTxField.backgroundColor = kRGBAColor(0xF2F5F9, 1);
    self.phoneTxField.layer.cornerRadius = 8;
    self.phoneTxField.layer.masksToBounds = YES;
    self.phoneTxField.placeholder = @"请输入收货人电话";
    self.phoneTxField.textColor = k333Color;
    self.phoneTxField.font = [UIFont systemFontOfSize:14];
    self.phoneTxField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 12, 38)];
    self.phoneTxField.leftViewMode = UITextFieldViewModeAlways;
    [wView3 addSubview:self.phoneTxField];
    
    self.addressTxField = [[UITextField alloc] initWithFrame:CGRectMake(12, CGRectGetMaxY(self.phoneTxField.frame) + 10, wView3.frame.size.width - 12 * 2, 38)];
    self.addressTxField.backgroundColor = kRGBAColor(0xF2F5F9, 1);
    self.addressTxField.layer.cornerRadius = 8;
    self.addressTxField.layer.masksToBounds = YES;
    self.addressTxField.placeholder = @"请输入收货地址";
    self.addressTxField.textColor = k333Color;
    self.addressTxField.font = [UIFont systemFontOfSize:14];
    self.addressTxField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 12, 38)];
    self.addressTxField.leftViewMode = UITextFieldViewModeAlways;
    [wView3 addSubview:self.addressTxField];
    
    CGFloat scrollHeight = CGRectGetMaxY(wView3.frame);
    [self.scrollView setContentSize:CGSizeMake(0, scrollHeight)];
    
    UIView * bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kSafeBottomHeight - 56, kScreenWidth, kSafeBottomHeight + 56)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    
    self.orderPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 12, 120, 42)];
    self.orderPriceLabel.textColor = kRGBAColor(0xFF0000, 1);
    self.orderPriceLabel.font = [UIFont boldSystemFontOfSize:26];
    [bottomView addSubview:self.orderPriceLabel];
    
    self.rentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rentButton.frame = CGRectMake(bottomView.frame.size.width - 16 - 155, 12, 155, 42);
    self.rentButton.layer.cornerRadius = 21;
    self.rentButton.layer.masksToBounds = YES;
    self.rentButton.backgroundColor = [UIColor blackColor];
    [self.rentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.rentButton setTitle:@"租用" forState:UIControlStateNormal];
    self.rentButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.rentButton addTarget:self action:@selector(rentAction) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.rentButton];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [self.scrollView addGestureRecognizer:tap];
    
}

- (void)getData {
    NSArray * imgs = [self.model.imgs componentsSeparatedByString:@","];
    if (imgs.count > 0) {
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:imgs[0]]];
    }
    self.titLabel.text = self.model.goodsTitle;
    
    NSString *string = [NSString stringWithFormat:@"￥%.2f/天", self.model.orderFee];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange helloRange = [string rangeOfString:@"￥"];
    [attributedString setAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0]} range:helloRange];
    NSRange worldRange = [string rangeOfString:@"/天"];
    [attributedString setAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0]} range:worldRange];
    self.priceLabel.attributedText = attributedString;
    
    self.rentPrice = self.model.orderFee * 30;
    self.rentPriceLabel.text = [NSString stringWithFormat:@"￥%.2f", self.rentPrice];
    self.depositPriceLabel.text = [NSString stringWithFormat:@"押金:￥%d", self.model.payAmount];
    self.sendPriceLabel.text = @"￥0";
    
    NSString *orderString = [NSString stringWithFormat:@"￥%.2f", self.rentPrice];
    NSMutableAttributedString *attributedString2 = [[NSMutableAttributedString alloc] initWithString:orderString];
    NSRange helloRange2 = [orderString rangeOfString:@"￥"];
    [attributedString2 setAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0]} range:helloRange2];
    self.orderPriceLabel.attributedText = attributedString2;
    
}

-(void)buttonAction:(UIButton *)button {
    for (int i = 0; i < 3; i++) {
        UIButton * btn = [self.view viewWithTag:1000 + i];
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitleColor:k333Color forState:UIControlStateNormal];
    }
    button.backgroundColor = kRGBAColor(0x5F6FFF, 1);
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    self.rentPrice = self.model.orderFee * ((button.tag - 1000) + 1) * 30;
    self.rentPriceLabel.text = [NSString stringWithFormat:@"￥%.2f", self.rentPrice];
    
    NSString *orderString = [NSString stringWithFormat:@"￥%.2f", self.rentPrice];
    NSMutableAttributedString *attributedString2 = [[NSMutableAttributedString alloc] initWithString:orderString];
    NSRange helloRange2 = [orderString rangeOfString:@"￥"];
    [attributedString2 setAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0]} range:helloRange2];
    self.orderPriceLabel.attributedText = attributedString2;
}

-(void)rentAction {
    if (kUid.length == 0) {
        ZZLoginViewController * vc = [[ZZLoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    if (self.nameTxField.text.length == 0) {
        [MBProgressHUD showMessage:@"请输入收货人姓名" toView:self.view];
        return;
    }
    if (self.phoneTxField.text.length == 0) {
        [MBProgressHUD showMessage:@"请输入收货人电话" toView:self.view];
        return;
    }
    if (self.addressTxField.text.length == 0) {
        [MBProgressHUD showMessage:@"请输入收货地址" toView:self.view];
        return;
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", kBaseUrl, kPay];
//    NSDictionary *params = @{@"amt": [NSString stringWithFormat:@"%f", self.rentPrice],
//                                 @"payType" : @(2)
//                                 };
    NSDictionary *params = @{@"amt": [NSString stringWithFormat:@"%f", 0.01],
                                 @"payType" : @(2)
                                 };
    
    [kFFNetManager POST:urlString parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject:~~~%@", responseObject);
        if ([responseObject[@"code"] integerValue] == 200) {
            NSDictionary * dic = responseObject[@"result"];
            self.oripay = [NSString stringWithFormat:@"%@", dic[@"oriPayParam"]];
            //应用注册scheme,在Info.plist定义URL types
            NSString *appScheme = @"zuzubao123";
            // NOTE: 调用支付结果开始支付
            [[AlipaySDK defaultService] payOrder:self.oripay fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut = %@",resultDic);
            }];
        }else {

        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

-(void)hideKeyBoard {
    [self.view endEditing:YES];
}

- (void)keyboardWillShow:(NSNotification *)not
{
    NSDictionary *userInfo = [not userInfo];
          
        // 获取键盘的最终尺寸
//        CGSize keyboardSize = [[userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue] size];
          
        // 根据键盘的尺寸调整视图或滚动视图的内容偏移量
        // 假设你有一个 UIScrollView 名为 scrollView
        self.scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 300, 0.0);
        self.scrollView.scrollIndicatorInsets = self.scrollView.contentInset;
          
        // 滚动视图以确保文本字段可见
        // 假设你的文本字段是 textField
        CGRect textFieldRect = [self.view.window convertRect:self.addressTxField.bounds fromView:self.addressTxField];
        CGFloat adjust = textFieldRect.origin.y - self.scrollView.contentOffset.y;
        if (adjust < 0) {
            self.scrollView.contentOffset = CGPointMake(0, adjust);
        }
}

- (void)keyboardWillHide:(NSNotification *)not
{
    // 重置视图的 contentInset 和 contentOffset
    self.scrollView.contentInset = UIEdgeInsetsZero;
    self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
    self.scrollView.contentOffset = CGPointZero;
}

@end
